//
//  HealthMoodViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-21.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "HealthMoodViewController.h"
#import "HealthNaviTitleView.h"
#import "AFURLSessionManager.h"
#import "XHImageViewer.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "MainViewController.h"

@interface HealthMoodViewController ()<UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,XHImageViewerDelegate,UITextViewDelegate>
{
    //存取图片个数
    NSMutableArray *imageArrays;
    //存取删除图片上button个数
    NSMutableArray *buttonArrays;
    //存取图片的url
    NSMutableArray *imageURlArrays;
    NSMutableArray *halfImageURL;
    NSInteger picCount;
}
/**
 *  自定义的naviBarTitleView;
 */
@property (nonatomic, strong) HealthNaviTitleView *healthNaviTitleView;
/**
 *  健康记录
 */
@property (strong, nonatomic) IBOutlet UITextView *healthMoodTextView;


@property (strong, nonatomic) IBOutlet UILabel *placeholderlable;


@property (strong, nonatomic) IBOutlet UIButton *cameraButton;
/**
 *  上传的字典
 */
@property (nonatomic, strong) NSMutableDictionary *uploadDic;
/**
 *  添加图片的button
 */
@property (strong, nonatomic) IBOutlet UIButton *addPhoto;
/**
 *  用来放图片和文字的视图
 */
@property (strong, nonatomic) IBOutlet UIView *bigView;
/**
 *  又来存放图片的地址
 */
@property (nonatomic, strong) NSMutableArray *picArray;

@property (nonatomic, strong) UIButton *rightButton;
@end

@implementation HealthMoodViewController

- (NSMutableArray *)picArray{
    if (_picArray == nil) {
        self.picArray = [NSMutableArray array];
    }
    return _picArray;
}

- (NSMutableDictionary *)uploadDic{
    if (_uploadDic == nil) {
        self.uploadDic = [NSMutableDictionary dictionary];
    }
    return _uploadDic;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    picCount = 0;
    if (kScreenWidth == 414) {
        self.bigView.frame = CGRectMake(0, 10, kScreenWidth, 176);
        self.healthMoodTextView.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
    }
    self.healthMoodTextView.returnKeyType = UIReturnKeyDone;
    self.healthNaviTitleView = [[[NSBundle mainBundle] loadNibNamed:@"HealthNaviTitleView" owner:self options:nil] lastObject];
    self.healthNaviTitleView.titleViewDate.text = self.timeStr;
    self.healthNaviTitleView.titleViewTitle.text = @"健康心情";
    self.view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.navigationItem.titleView = self.healthNaviTitleView;
    self.healthMoodTextView.delegate = self;
    [self setNaviBarAttribute];
    self.addPhoto.hidden = YES;
    buttonArrays=[[NSMutableArray alloc]init];
    imageArrays=[[NSMutableArray alloc]init];
    imageURlArrays=[[NSMutableArray alloc]init];
    halfImageURL=[[NSMutableArray alloc]init];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.healthMoodTextView becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(0, 0, 23, 23);
    [self.rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
}


/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction{
    [self _parsePersonalDataSource:kBaseURL];
    
}

- (IBAction)cameraButtonAction:(UIButton *)sender {
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    [alert show];
}

- (IBAction)addPhoneButtonAction:(UIButton *)sender {
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"照相机", @"图片库",nil];
    [alert show];
}

#pragma mark - 图片的AlertDelegate -
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized)
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机被禁用"
                                                           message:@"请在iPhone的“设置-隐私-相机”中允许安好访问您的相机。"
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil, nil];
            [alert show];
        }else{
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
                pickerImage.delegate = self;
                pickerImage.allowsEditing = YES;
                //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
                pickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;//指定使用相机
                [self presentViewController:pickerImage animated:YES completion:nil];
            }
            else{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
        }
        
    }
    else if(buttonIndex == 2)
    {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
            pickerImage.delegate = self;
            NSArray * array1 = [NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
            pickerImage.mediaTypes = array1;
            pickerImage.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.allowsEditing = YES;
            [self presentViewController:pickerImage animated:YES completion:nil];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}

#pragma mark  - ImagepickviewcontrollerDelegate 选择图片后的代理方法 -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        [self postImage:info];
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        [picker dismissViewControllerAnimated:YES completion:^{
        }];
    }
}



#pragma mark - 网路数据上传 -
- (void)_parsePersonalDataSource:(NSString *)urlString{
    [self showActionView];
    NSString *time = [self setNewTime];
    [self getTextFieldText];
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/logadd/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [self.uploadDic setValue:kPlatform forKey:@"platform"];
    [self.uploadDic setValue:kVersion forKey:@"version"];
    [self.uploadDic setValue:@"1" forKey:@"type"];
    [self.uploadDic setValue:time forKey:@"daytime"];
    NSString *pic = [self returnPicStr:self.picArray];
    if (pic.length > 0) {
        [self.uploadDic setValue:pic forKey:@"pic"];
    }
    [manager POST:postURL parameters:self.uploadDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:@"发送失败"];
        }else{
            MyNSLog("========%@========", [responseObject objectForKey:@"msg"]);
            [self.rightButton removeTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
            [self performSelector:@selector(afterMinu) withObject:nil afterDelay:1];
            [self showCustomHudSingleLine:@"今日心情已成功创建"];
        }
    } failure:nil];
}


- (void)postImage:(NSDictionary *)dic
{
    [self showActionView];
    UIImage *postImage = [dic objectForKey:UIImagePickerControllerEditedImage];
    NSData* imageData = UIImageJPEGRepresentation(postImage, 0.5);
    NSDictionary *postDic = @{@"platform": kPlatform,@"version":kVersion};
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@user/uploadlogpic/",kBaseURL] parameters:postDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"george.jpg" mimeType:@"image/jpeg"];
        
    } error:nil];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            MyNSLog("Error: %@", error);
            [self hiddenActionView];
        } else {
            //图片上传成功
            NSString *status = [NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"1"]) {
                [imageURlArrays addObject:[[responseObject valueForKey:@"data"] valueForKey:@"url"]];
                
                if (kScreenWidth == 414) {
                    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15 + ((kScreenWidth - 30 - 66 * 4) / 3 + 66) * imageArrays.count, 100, 66, 66)];
                    imageView.image = postImage;
                    imageView.tag = imageArrays.count + 3000;
                    imageView.layer.cornerRadius = 3;
                    imageView.layer.masksToBounds = YES;
                    //在imageview上的button（用于删除）
                    UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    imageButton.frame = CGRectMake(15 + ((kScreenWidth - 30 - 66 * 4) / 3 + 66) * imageArrays.count,100, 66, 66);
                    [imageButton addTarget:self action:@selector(dodelete:) forControlEvents:UIControlEventTouchUpInside];
                    imageButton.tag = imageArrays.count;
                    [imageArrays addObject:imageView];
                    [buttonArrays addObject:imageButton];
                    if (imageArrays.count >= 1) {
                        self.addPhoto.frame=CGRectMake(15 + ((kScreenWidth - 30 - 66 * 4) / 3 + 66) * imageArrays.count, 100, 66, 66);
                        self.addPhoto.hidden = NO;
                    }
                    [self.bigView addSubview:imageView];
                    [self.bigView addSubview:imageButton];
                    NSDictionary *dic = [responseObject objectForKey:@"data"];
                    [self.picArray addObject:[dic objectForKey:@"pic"]];
                    [self hiddenActionView];
                    
                }else{
                    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(15 + ((kScreenWidth - 30 - 55 * 4) / 3 + 55) * imageArrays.count, 100, 55, 55)];
                    imageView.image = postImage;
                    imageView.tag = imageArrays.count + 3000;
                    imageView.layer.cornerRadius = 3;
                    imageView.layer.masksToBounds = YES;
                    //在imageview上的button（用于删除）
                    UIButton *imageButton = [UIButton buttonWithType:UIButtonTypeCustom];
                    //                imageButton.frame = CGRectMake(15 + 78 * imageArrays.count,100, 55, 55);
                    imageButton.frame = CGRectMake(15 + ((kScreenWidth - 30 - 55 * 4) / 3 + 55) * imageArrays.count,100, 55, 55);
                    [imageButton addTarget:self action:@selector(dodelete:) forControlEvents:UIControlEventTouchUpInside];
                    imageButton.tag = imageArrays.count;
                    [imageArrays addObject:imageView];
                    [buttonArrays addObject:imageButton];
                    if (imageArrays.count >= 1) {
                        //                    self.addPhoto.frame=CGRectMake(15 + 78 * imageArrays.count, 100, 55, 55);
                        self.addPhoto.frame=CGRectMake(15 + ((kScreenWidth - 30 - 55 * 4) / 3 + 55) * imageArrays.count, 100, 55, 55);
                        self.addPhoto.hidden = NO;
                    }
                    [self.bigView addSubview:imageView];
                    [self.bigView addSubview:imageButton];
                    NSDictionary *dic = [responseObject objectForKey:@"data"];
                    [self.picArray addObject:[dic objectForKey:@"pic"]];
                    [self hiddenActionView];
                }
            }else
            {
            }
        }
    }];
    [uploadTask resume];
}

- (void)afterMinu{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dodelete:(UIButton *)sender{
    picCount=sender.tag;
    UIActionSheet *actSheet=[[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"查看大图" otherButtonTitles:@"删除", nil];
    [actSheet showInView:[[[UIApplication sharedApplication] delegate] window]];

}


#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0) {
        /*
        int count = [imageArrays count];
        // 1.封装图片数据
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = [NSURL URLWithString:[imageURlArrays objectAtIndex:i]]; // 图片路径
            UIImageView * imageView1 = (UIImageView *)[self.view viewWithTag:3000 + i];
            photo.srcImageView = imageView1; // 来源于哪个UIImageView
            [photos addObject:photo];
        }
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        browser.currentPhotoIndex = picCount; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        [browser show];
        */
        XHImageViewer *imageViewer = [[XHImageViewer alloc] init];
        imageViewer.delegate = self;
        [imageViewer showWithImageViews:imageArrays selectedView:(UIImageView *)[self.view viewWithTag:picCount+3000]];
        
    }else if (buttonIndex==1)
    {
        //删除UI上的控件（imageview和button）
        [[imageArrays objectAtIndex:picCount] removeFromSuperview];
        [[buttonArrays objectAtIndex:picCount] removeFromSuperview];
        //删除数组的值
        [imageArrays removeObjectAtIndex:picCount];
        [buttonArrays removeObjectAtIndex:picCount];
        [imageURlArrays removeObjectAtIndex:picCount];
        [self.picArray removeObjectAtIndex:picCount];
        
        
        if (kScreenWidth == 414) {
            for (NSInteger i=0; i<imageArrays.count; i++) {
                [[imageArrays objectAtIndex:i] setFrame:CGRectMake(15+i*106, 100, 66, 66)];
                [[buttonArrays objectAtIndex:i] setFrame:CGRectMake(15+i*106, 100, 66, 66)];
                [((UIButton *)[buttonArrays objectAtIndex:i])setTag:i];
            }
            self.addPhoto.frame=CGRectMake(15 +[imageArrays count] * 106, 100, 66, 66);
        }else{
            for (NSInteger i=0; i<imageArrays.count; i++) {
                [[imageArrays objectAtIndex:i] setFrame:CGRectMake(15+i*78, 100, 55, 55)];
                [[buttonArrays objectAtIndex:i] setFrame:CGRectMake(15+i*78, 100, 55, 55)];
                [((UIButton *)[buttonArrays objectAtIndex:i])setTag:i];
            }
            self.addPhoto.frame=CGRectMake(15 +[imageArrays count] * 78, 100, 55, 55);
        }
        if (imageArrays.count < 1) {
            self.addPhoto.hidden = YES;
        }
        
    }
}


#pragma mark - 获取textField的内容 -
- (void)getTextFieldText{
    [self.uploadDic setValue:self.healthMoodTextView.text forKey:@"description"];
}

#pragma mark - 获取当前的时间 -
- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}


- (NSString *)returnPicStr:(NSMutableArray *)array{
    if (array.count == 1) {
        return [NSString stringWithFormat:@"%@",array[0]];
    }else if (array.count == 2){
        return [NSString stringWithFormat:@"%@,%@",array[0],array[1]];
    }else if (array.count == 3){
        return [NSString stringWithFormat:@"%@,%@,%@",array[0],array[1],array[2]];
    }else if (array.count == 4){
        return [NSString stringWithFormat:@"%@,%@,%@,%@",array[0],array[1],array[2],array[3]];
    }else if (array.count == 0){
        return  [NSString stringWithFormat:@""];
    }else{
        return nil;
    }
}


#pragma mark - textField的代理方法 -

-(void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length>0) {
        self.placeholderlable.hidden = YES;
    }else
    {
        self.placeholderlable.hidden = NO;
    }
    
}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    [self.healthMoodTextView resignFirstResponder];
    
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }else
    {
        return YES;
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
